package com.pethospital.service.impl;

import com.pethospital.dao.PetDao;
import com.pethospital.dao.impl.PetDaoImpl;
import com.pethospital.entity.PageResult;
import com.pethospital.entity.Pet;
import com.pethospital.service.PetService;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

/**
 * 宠物服务实现类
 * Pet Service Implementation
 * 
 * @author PetHospital System
 * @version 1.0
 */
public class PetServiceImpl implements PetService {
    
    private PetDao petDao = new PetDaoImpl();
    
    @Override
    public Pet getPetById(Integer petId) {
        if (petId == null || petId <= 0) {
            return null;
        }
        return petDao.findById(petId);
    }
    
    @Override
    public List<Pet> getPetsByOwnerId(Integer ownerId) {
        System.out.println("DEBUG: PetServiceImpl.getPetsByOwnerId() 被调用，ownerId: " + ownerId);

        if (ownerId == null || ownerId <= 0) {
            System.out.println("DEBUG: ownerId 无效，返回 null");
            return null;
        }

        List<Pet> pets = petDao.findByOwnerId(ownerId);
        System.out.println("DEBUG: DAO 返回的宠物数量: " + (pets != null ? pets.size() : "null"));

        return pets;
    }

    @Override
    public List<Pet> getRecentPetsByOwnerId(Integer ownerId, int limit) {
        if (ownerId == null || ownerId <= 0) {
            return new java.util.ArrayList<>();
        }
        if (limit <= 0) limit = 5;

        return petDao.findRecentByOwnerId(ownerId, limit);
    }
    
    @Override
    public boolean addPet(Pet pet) {
        // 验证宠物数据
        String validationResult = validatePet(pet, false);
        if (validationResult != null) {
            return false;
        }
        
        // 设置默认值
        if (pet.getStatus() == null || pet.getStatus().trim().isEmpty()) {
            pet.setStatus("healthy");
        }
        
        return petDao.insert(pet) > 0;
    }
    
    @Override
    public boolean updatePet(Pet pet) {
        if (pet == null || pet.getPetId() == null) {
            return false;
        }
        
        // 验证宠物数据
        String validationResult = validatePet(pet, true);
        if (validationResult != null) {
            return false;
        }
        
        return petDao.update(pet) > 0;
    }
    
    @Override
    public boolean deletePet(Integer petId) {
        if (petId == null || petId <= 0) {
            return false;
        }
        
        return petDao.delete(petId) > 0;
    }
    
    @Override
    public boolean batchDeletePets(Integer[] petIds) {
        if (petIds == null || petIds.length == 0) {
            return false;
        }
        
        return petDao.batchDelete(petIds) > 0;
    }
    
    @Override
    public List<Pet> getAllPets() {
        return petDao.findAll();
    }
    
    @Override
    public PageResult<Pet> getPetsByPage(int currentPage, int pageSize) {
        if (currentPage <= 0) currentPage = 1;
        if (pageSize <= 0) pageSize = 10;
        
        return petDao.findByPage(currentPage, pageSize);
    }
    
    @Override
    public PageResult<Pet> getPetsByOwnerAndPage(Integer ownerId, int currentPage, int pageSize) {
        if (ownerId == null || ownerId <= 0) {
            return new PageResult<>();
        }
        if (currentPage <= 0) currentPage = 1;
        if (pageSize <= 0) pageSize = 10;
        
        return petDao.findByOwnerIdAndPage(ownerId, currentPage, pageSize);
    }
    
    @Override
    public PageResult<Pet> searchPets(String petName, String petType, String breed,
                                    String status, Integer ownerId, int currentPage, int pageSize) {
        if (currentPage <= 0) currentPage = 1;
        if (pageSize <= 0) pageSize = 10;

        return petDao.findByCondition(petName, petType, breed, status, ownerId, currentPage, pageSize);
    }

    @Override
    public PageResult<Pet> searchPetsWithSort(String petName, String petType, String breed,
                                            String status, Integer ownerId, String sortField,
                                            String sortOrder, int currentPage, int pageSize) {
        if (currentPage <= 0) currentPage = 1;
        if (pageSize <= 0) pageSize = 10;

        return petDao.findByConditionWithSort(petName, petType, breed, status, ownerId,
                                            sortField, sortOrder, currentPage, pageSize);
    }
    
    @Override
    public long getTotalPetCount() {
        return petDao.countAll();
    }
    
    @Override
    public long getPetCountByOwner(Integer ownerId) {
        if (ownerId == null || ownerId <= 0) {
            return 0;
        }
        return petDao.countByOwnerId(ownerId);
    }
    
    @Override
    public long getPetCountByType(String petType) {
        if (petType == null || petType.trim().isEmpty()) {
            return 0;
        }
        return petDao.countByPetType(petType);
    }
    
    @Override
    public long getPetCountByStatus(String status) {
        if (status == null || status.trim().isEmpty()) {
            return 0;
        }
        return petDao.countByStatus(status);
    }

    @Override
    public long getTodayRegisteredPetCount() {
        return petDao.countTodayRegistered();
    }

    @Override
    public long getTodayRegisteredPetCountByOwnerId(Integer ownerId) {
        if (ownerId == null || ownerId <= 0) {
            return 0;
        }
        return petDao.countTodayRegisteredByOwnerId(ownerId);
    }
    
    @Override
    public boolean updatePetStatus(Integer petId, String status) {
        if (petId == null || petId <= 0 || status == null || status.trim().isEmpty()) {
            return false;
        }
        
        // 验证状态值
        if (!"healthy".equals(status) && !"sick".equals(status) && !"treatment".equals(status)) {
            return false;
        }
        
        return petDao.updateStatus(petId, status) > 0;
    }
    
    @Override
    public boolean updatePetPhoto(Integer petId, String photoUrl) {
        if (petId == null || petId <= 0) {
            return false;
        }
        
        return petDao.updatePhoto(petId, photoUrl) > 0;
    }
    
    @Override
    public List<Object[]> getPetTypeStatistics() {
        return petDao.getPetTypeStatistics();
    }
    
    @Override
    public List<Object[]> getStatusStatistics() {
        return petDao.getStatusStatistics();
    }
    
    @Override
    public String validatePet(Pet pet, boolean isUpdate) {
        if (pet == null) {
            return "宠物信息不能为空";
        }
        
        // 验证宠物姓名
        if (pet.getPetName() == null || pet.getPetName().trim().isEmpty()) {
            return "宠物姓名不能为空";
        }
        if (pet.getPetName().length() > 50) {
            return "宠物姓名长度不能超过50个字符";
        }
        
        // 验证宠物类型
        if (pet.getPetType() == null || pet.getPetType().trim().isEmpty()) {
            return "宠物类型不能为空";
        }
        if (pet.getPetType().length() > 30) {
            return "宠物类型长度不能超过30个字符";
        }
        
        // 验证品种
        if (pet.getBreed() != null && pet.getBreed().length() > 50) {
            return "品种长度不能超过50个字符";
        }
        
        // 验证性别
        if (pet.getGender() != null && !pet.getGender().trim().isEmpty()) {
            if (!"male".equals(pet.getGender()) && !"female".equals(pet.getGender())) {
                return "性别只能是male或female";
            }
        }
        
        // 验证年龄
        if (pet.getAge() != null && pet.getAge() < 0) {
            return "年龄不能为负数";
        }
        if (pet.getAge() != null && pet.getAge() > 300) {
            return "年龄不能超过300个月";
        }
        
        // 验证体重
        if (pet.getWeight() != null && pet.getWeight().compareTo(BigDecimal.ZERO) < 0) {
            return "体重不能为负数";
        }
        if (pet.getWeight() != null && pet.getWeight().compareTo(new BigDecimal("1000")) > 0) {
            return "体重不能超过1000kg";
        }
        
        // 验证毛色
        if (pet.getColor() != null && pet.getColor().length() > 30) {
            return "毛色长度不能超过30个字符";
        }
        
        // 验证主人ID
        if (!isUpdate && (pet.getOwnerId() == null || pet.getOwnerId() <= 0)) {
            return "主人ID不能为空";
        }
        
        // 验证描述
        if (pet.getDescription() != null && pet.getDescription().length() > 500) {
            return "描述长度不能超过500个字符";
        }
        
        // 验证状态
        if (pet.getStatus() != null && !pet.getStatus().trim().isEmpty()) {
            if (!"healthy".equals(pet.getStatus()) && !"sick".equals(pet.getStatus()) && 
                !"treatment".equals(pet.getStatus())) {
                return "状态只能是healthy、sick或treatment";
            }
        }
        
        return null; // 验证通过
    }
    
    @Override
    public boolean hasPermission(Integer petId, Integer userId, boolean isAdmin) {
        if (petId == null || petId <= 0 || userId == null || userId <= 0) {
            return false;
        }
        
        // 管理员有所有权限
        if (isAdmin) {
            return true;
        }
        
        // 普通用户只能操作自己的宠物
        Pet pet = petDao.findById(petId);
        return pet != null && pet.getOwnerId().equals(userId);
    }
    
    @Override
    public List<String> getBreedsByType(String petType) {
        // 这里可以根据宠物类型返回对应的品种列表
        // 为了简化，这里返回一些常见的品种
        if ("狗".equals(petType) || "dog".equalsIgnoreCase(petType)) {
            return Arrays.asList("金毛", "拉布拉多", "泰迪", "哈士奇", "萨摩耶", "边牧", "德牧", "比熊", "柯基", "博美");
        } else if ("猫".equals(petType) || "cat".equalsIgnoreCase(petType)) {
            return Arrays.asList("英短", "美短", "布偶", "暹罗", "波斯", "缅因", "折耳", "加菲", "俄蓝", "土猫");
        } else {
            return Arrays.asList("混种", "其他");
        }
    }
    
    @Override
    public List<String> getAllPetTypes() {
        return Arrays.asList("狗", "猫", "鸟", "兔子", "仓鼠", "龟", "鱼", "其他");
    }
    
    @Override
    public List<Pet> getPetsByAgeRange(Integer minAge, Integer maxAge) {
        // 这里需要在DAO中实现相应的方法
        // 为了简化，暂时返回空列表
        return Arrays.asList();
    }
    
    @Override
    public List<Pet> getPetsByWeightRange(Double minWeight, Double maxWeight) {
        // 这里需要在DAO中实现相应的方法
        // 为了简化，暂时返回空列表
        return Arrays.asList();
    }
    
    @Override
    public List<Pet> getPetsNeedingAttention() {
        // 查询状态为sick或treatment的宠物
        List<Pet> sickPets = petDao.findByCondition(null, null, null, "sick", null, 1, 100).getData();
        List<Pet> treatmentPets = petDao.findByCondition(null, null, null, "treatment", null, 1, 100).getData();
        
        sickPets.addAll(treatmentPets);
        return sickPets;
    }
    
    @Override
    public int importPets(List<Pet> pets) {
        if (pets == null || pets.isEmpty()) {
            return 0;
        }
        
        int successCount = 0;
        for (Pet pet : pets) {
            if (addPet(pet)) {
                successCount++;
            }
        }
        
        return successCount;
    }
    
    @Override
    public List<Pet> exportPets(Integer ownerId) {
        if (ownerId != null) {
            return petDao.findByOwnerId(ownerId);
        } else {
            return petDao.findAll();
        }
    }
}
